import hashlib
import os
import random
import string
import time

from flask import jsonify, request, session, render_template, redirect, url_for, g
from werkzeug.security import check_password_hash, generate_password_hash

from models import db
from models.index import User, Follow, Category, News
from utils.img_qiniu import upload_image_to_qiniu
from . import user_bp


@user_bp.route("/follow", methods=["POST"])
def follow():

    action = request.json.get('action')
    news_author_id = request.json.get('user_id')
    user_id = session.get('user_id')
    if action == 'do':

        news_author = db.session.query(User).filter(User.id == news_author_id).first()
        if not user_id:
            return jsonify(
                {
                    'errno': 3002,
                    'errmsg': '请先登录'
                }
            )
        if user_id in [x.id for x in news_author.followers]:
            return jsonify(
                {
                    'errno': 3001,
                    'errmsg': '已经关注啦'
                }
            )

        try:
            follow = Follow(followed_id=news_author_id, follower_id=user_id)
            db.session.add(follow)
            db.session.commit()

            ret = {
                'errno': 0,
                'errmsg': '关注成功'
            }

            return jsonify(ret)


        except Exception as ret:
            ret = {
                "errno": 3003,
                "errmsg": "关注失败..."
            }

            return jsonify(ret)
    else:

        try:
            follow = db.session.query(Follow).filter(
                Follow.followed_id == news_author_id, Follow.follower_id == user_id).first()
            db.session.delete(follow)
            db.session.commit()
            ret = {
                'errno': 0,
                'errmsg': '取消关注成功'
            }
            return jsonify(ret)
        except Exception as e:
            db.session.rollback()
            ret = {
                'errno': 3004,
                'errmsg': '取消关注失败'

            }

            return jsonify(ret)


@user_bp.route('/user_center')
def user_center():
    if not g.user:
        return redirect(url_for("index.index"))

    return render_template('index/user.html', user=g.user)


@user_bp.route("/user_base_info")
def user_base_info():
    if not g.user:
        return redirect(url_for("index.index"))

    return render_template("index/user_base_info.html", user=g.user)


@user_bp.route('/basic', methods=['GET', 'POST'])
def user_basic():
    if not g.user:
        ret = {
            'errno': 4002,
            'errmsg': '没有此用户'
        }
        return jsonify(ret)
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')

    g.user.nick_name = nick_name
    g.user.signature = signature
    g.user.gender = gender

    db.session.commit()

    ret = {
        'errno': 0,
        'errmsg': '修改成功'
    }
    return jsonify(ret)


@user_bp.route("/user_pass_info")
def user_pass_info():
    if not g.user:
        return redirect(url_for("index.index"))
    return render_template("index/user_pass_info.html")


@user_bp.route('/password', methods=['GET', 'POST'])
def user_password():
    if not g.user:
        return redirect(url_for("index.index"))
    new_password = request.json.get('new_password')
    old_password = request.json.get('old_password')

    if g.user and check_password_hash(g.user.password_hash, old_password):
        g.user.password_hash = generate_password_hash(new_password)
        db.session.commit()
        session.clear()
        ret = {
            'errno': 0,
            'errmsg': '修改密码成功,请重新登录'
        }

    else:
        ret = {
            'errno': 4004,
            'errmsg': '原密码错误'
        }

    return jsonify(ret)


@user_bp.route('/user_pic_info')
def user_pic_info():
    if not g.user:
        return redirect(url_for("index.index"))
    return render_template('index/user_pic_info.html', user=g.user)


@user_bp.route('/avatar', methods=['GET', 'POST'])
def user_avatar():
    if not g.user:
        return redirect(url_for("index.index"))

    if g.user.avatar_url:
        db_avatar_url = g.user.avatar_url
        qiniu_url = "http://qhrpvuoua.hn-bkt.clouddn.com/"
        if qiniu_url in db_avatar_url:
            db_avatar_url = db_avatar_url.replace(qiniu_url, "")
            url = './static/upload/' + db_avatar_url
            os.remove(url)
    # 生成图片随机名称
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))
    # 获取前端上传的图片
    img = request.files.get('avatar')
    # print('当前绝对路径=========',BASEDIR)
    # 存放图片的路径
    path = './static/upload/'
    imgName = ran_str + img.filename
    file_path = path + imgName
    img.save(file_path)
    qiniu_avatar_url = upload_image_to_qiniu(file_path, imgName)
    g.user.avatar_url = qiniu_avatar_url
    db.session.commit()
    return jsonify(
        {
            'errno': 0,
            'errmsg': '修改成功',
            'avatar_url': file_path
        }
    )


@user_bp.route('/user_follow')
def user_follow():
    if not g.user:
        return redirect(url_for("index.index"))

    # 获取当前需要展示的页数
    page = int(request.args.get("page", 1))

    news_author_followers_id = [x.id for x in g.user.followed]
    paginate = g.user.followers.paginate(page, 2, False)
    return render_template("index/user_follow.html", paginate=paginate,
                           news_author_followers_id=news_author_followers_id)


@user_bp.route('/user_collection')
def user_collection():
    if not g.user:
        return redirect(url_for("index.index"))

    page = int(request.args.get('page', 1))
    # 查询用户
    user_id = session.get("user_id")
    user = db.session.query(User).filter(User.id == user_id).first()
    paginate = user.collection_news.paginate(page, 2, False)

    return render_template("index/user_collection.html", paginate=paginate)


@user_bp.route('/user_news_release')
def user_news_release():
    if not g.user:
        return redirect(url_for("index.index"))

    category_list = db.session.query(Category).filter(Category.id != 1).all()
    return render_template("index/user_news_release.html", category_list=category_list)


@user_bp.route('/release', methods=['POST'])
def user_release():
    if not g.user:
        return redirect(url_for("index.index"))

    title = request.form.get("title")
    category = request.form.get("category")
    digest = request.form.get("digest")
    content = request.form.get("content")
    f = request.files.get("index_image")

    # print(title, category, digest, content, f)
    news = News()
    news.title = title
    news.category_id = category
    news.source = "个人发布"
    news.digest = digest
    news.content = content
    news.user_id = session.get("user_id")
    news.status = 1  # 1代表 正在审核

    if f:
        file_hash = hashlib.md5()
        file_hash.update((f.filename + time.ctime()).encode("utf-8"))
        file_name = file_hash.hexdigest() + f.filename[f.filename.rfind("."):]

        # 将路径改为static/upload下
        path_file_name = "./static/upload/" + file_name

        # 用新的随机的名字当做图片的名字
        f.save(path_file_name)

        # 将这个图片上传到七牛云
        qiniu_image_url = upload_image_to_qiniu(path_file_name, file_name)
        news.index_image_url = qiniu_image_url

    db.session.add(news)
    db.session.commit()

    ret = {
        "errno": 0,
        "errmsg": "成功"
    }

    return jsonify(ret)


@user_bp.route('/user_news_list')
def user_news_list():
    if not g.user:
        return redirect(url_for("index.index"))

    page = int(request.args.get('page', 1))
    # 查询当前用户
    user_id = session.get("user_id")
    user = db.session.query(User).filter(User.id == user_id).first()
    # 获取当前用户的所有新闻
    news_paginate = user.news.paginate(page, 2, False)

    return render_template('index/user_news_list.html', news_paginate=news_paginate)
